/*
 * Copyright 2016 Kejun Xia
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.shipdream.lib.ohos.mvc;

import ohos.agp.components.Component;
import ohos.agp.components.LayoutScatter;
import ohos.agp.window.dialog.CommonDialog;
import ohos.app.Context;

/**
 * This dialog fragment can either use {@link CommonDialog} to build a alert dialog or use
 * {@link MvcFragment} as an nested fragment for custom view dialog, as a result the underlying
 * doesn't need to be designed with awareness how it is going to be used and can be reused as a
 * normal fragment as well. This class is FINAL and don't extend this class to custom your dialog.
 * <p/>
 */
public abstract class MvcDialogFragment extends CommonDialog {

    protected Context context;


    private EventRegister eventRegister;

    public MvcDialogFragment(Context context) {
        super(context);
        this.context = context;
    }

    @Override
    protected void onCreate() {
        super.onCreate();
        Mvc.graph().inject(this);

        eventRegister = new EventRegister(this);
        eventRegister.registerEventBuses();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        eventRegister.unregisterEventBuses();
        Mvc.graph().release(this);
    }

    /**
     * Handy method to post an event to other views directly. However, when possible, it's
     * recommended to post events from controllers to views to keep views' logic simple.
     *
     * @param event
     */
    protected void postEvent2V(Object event) {
        eventRegister.postEvent2V(event);
    }

    public abstract Component onCreateView(LayoutScatter layoutScatter);

    public void showDialogFragment() {
        Component component = onCreateView(LayoutScatter.getInstance(context));
        setContentCustomComponent(component);
        show();
    }
}
